package com.summli.basic.class07;

/**
 * 打印一颗二叉树
 */
public class Code05_PrintBinaryTree {

    public static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node(int data) {
            this.value = data;
        }
    }
    public static void printTree(Node head) {
        System.out.println("Binary Tree");
        printInOrder(head,0,"H",17);
        System.out.println();
    }

    private static void printInOrder(Node node, int level, String flag, int len) {
        if(node == null){
            return;
        }
        printInOrder(node.right,level+1, "V", 17);

        String value = flag+String.valueOf(node.value)+flag;
        int result = len - value.length();
        int left = result / 2;
        int right = result - left;
        value = getSpace(len*level)+getSpace(left)+value+getSpace(right);
        System.out.println(value);
        printInOrder(node.left, level+1, "^", 17);
    }

    private static String getSpace(int num) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < num; i++) {
            sb.append(" ");
        }
        return sb.toString();
    }
    public static void main(String[] args) {
        Node head = new Node(1);
        head.left = new Node(-222222222);
        head.right = new Node(3);
        head.left.left = new Node(Integer.MIN_VALUE);
        head.right.left = new Node(55555555);
        head.right.right = new Node(66);
        head.left.left.right = new Node(777);
        printTree(head);

        head = new Node(1);
        head.left = new Node(2);
        head.right = new Node(3);
        head.left.left = new Node(4);
        head.right.left = new Node(5);
        head.right.right = new Node(6);
        head.left.left.right = new Node(7);
        printTree(head);

        head = new Node(1);
        head.left = new Node(1);
        head.right = new Node(1);
        head.left.left = new Node(1);
        head.right.left = new Node(1);
        head.right.right = new Node(1);
        head.left.left.right = new Node(1);
        printTree(head);

    }
}
